package com.ds.admin.org.role;

import com.alibaba.fastjson.annotation.JSONField;
import com.ds.admin.iorg.role.IRoleForm;
import com.ds.admin.iorg.role.IRoleService;
import com.ds.common.JDSException;
import com.ds.common.org.CtOrgAdminManager;
import com.ds.common.org.CtRole;
import com.ds.common.util.StringUtility;
import com.ds.esb.config.EsbBeanAnnotation;
import com.ds.esd.client.ESDFacrory;
import com.ds.org.OrgManager;
import com.ds.org.Role;
import com.ds.org.RoleNotFoundException;
import com.ds.org.RoleType;
import com.ds.server.OrgManagerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@EsbBeanAnnotation()
public class RoleService implements IRoleService {

    public void saveRole(IRoleForm role) {
        CtRole ctRole = null;
        if (role.getRoleId() != null && !role.getRoleId().equals("")) {
            try {
                ctRole = (CtRole) OrgManagerFactory.getOrgManager().getRoleByID(role.getRoleId());
            } catch (RoleNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            ctRole = new CtRole();
            ctRole.setRoleId(UUID.randomUUID().toString());
        }

        if (role.getRoleType() == null) {
            ctRole.setType(RoleType.Role);
        } else {
            ctRole.setType(role.getRoleType());
        }

        try {
            ctRole.setSysId(ESDFacrory.getESDClient().getSpace().getSysId());
        } catch (JDSException e) {
            e.printStackTrace();
        }
        ctRole.setName(role.getName());
        CtOrgAdminManager.getInstance().saveRole(ctRole);

    }


    public void delRole(String roleId) {
        String[] roleIdArr = StringUtility.split(roleId, ";");
        for (String id : roleIdArr) {
            CtOrgAdminManager.getInstance().delRole(id);
        }
    }


    public Role getRoleInfo(String roleId, String roleType) throws RoleNotFoundException {
        Role ctRole = (CtRole) OrgManagerFactory.getOrgManager().getRoleByID(roleId);
        return ctRole;
    }


    public Role addRole(RoleType roleType, String sysId) {
        CtRole role = new CtRole();
        role.setType(roleType);
        role.setName("新建角色");
        role.setSysId(sysId);
        return role;
    }


    public List<Role> getRoleList(RoleType roleType) throws JDSException {
        List<Role> roleList = new ArrayList<>();
        List<Role> roles = getOrgManager().getAllRoles();
        for (Role role : roles) {
            if (role.getType().equals(roleType)) {
                roleList.add(role);
            }
        }
        return roleList;
    }


    @JSONField(serialize = false)
    private OrgManager getOrgManager() throws JDSException {
        OrgManager orgManager = OrgManagerFactory.getOrgManager();
        return orgManager;
    }
}
